import { ExpressMiddlewareInterface, Middleware } from 'routing-controllers';
import { Response, NextFunction } from 'express';
import { v4 as uuid } from 'uuid';
import { saveAuditLog } from '@utils/save-audit-log';
import { RequestWithId } from '@/interfaces';
import { logger } from '@utils/logger';

@Middleware({ type: 'before' })
export class AuditLogBeforeMiddleware implements ExpressMiddlewareInterface {
  use(req: RequestWithId, _res: Response, next: NextFunction) {
    // 生成 requestId 并挂载
    req.id = uuid();
    next();
  }
}

@Middleware({ type: 'after' })
export class AuditLogAfterMiddleware implements ExpressMiddlewareInterface {
  async use(req: RequestWithId, res: Response, next: NextFunction) {
    // 控制器方法执行完成后触发
    res.on('finish', async () => {
      try {
        await saveAuditLog(req, res);
      } catch (err) {
        logger.error(err.message);
        logger.error(err.stack);
      }
    });

    next();
  }
}
